package cn.wolfcode.luowowo.listener;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.Travel;
import cn.wolfcode.luowowo.redis.IStrategyRedisVO;
import cn.wolfcode.luowowo.redis.ITravelRedisVO;
import cn.wolfcode.luowowo.redis.util.RedisKeys;
import cn.wolfcode.luowowo.redis.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.redis.vo.TravelStatisVO;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.ITravelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 在spring容器启动时,对redis进行初始化操作
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyRedisVO strategyRedisVO;
    @Autowired
    private ITravelRedisVO travelRedisVO;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ITravelService travelService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //将所有的攻略查出来
        List<Strategy> list = strategyService.list();
        for (Strategy strategy : list) {
            //查询在redis中有没有存vo 点赞数 收藏数 分享数 评论数 阅读数
            String key = RedisKeys.STRATEGY_STATIS_VO.join(strategy.getId());
            //如果已经存在  就跳过初始化
            if (redisTemplate.hasKey(key)){
                continue;
            }
            //不存在的话  在进行初始化操作
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy,vo);
            vo.setStrategyId(strategy.getId());
            //将vo这些点赞信息设置到redis
            strategyRedisVO.setVoToRedis(vo);
        }
        //将所有的游记查出来
        List<Travel> travellist = travelService.list();
        for (Travel travel : travellist) {
            //查询在redis中有没有存vo 点赞数 收藏数 分享数 评论数 阅读数
            String key = RedisKeys.TRAVEL_STATIS_VO.join(travel.getId());
            //如果已经存在  就跳过初始化
            if (redisTemplate.hasKey(key)){
                continue;
            }
            //不存在的话  在进行初始化操作
            TravelStatisVO vo = new TravelStatisVO();
            BeanUtils.copyProperties(travel,vo);
            vo.setTravelId(travel.getId());
            //将vo这些点赞信息设置到redis
            travelRedisVO.setVoToRedis(vo);
        }
    }









}